package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.entity.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {

    //该类的作用：可以对比url地址
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求路径
        String requestURI = request.getRequestURI();
        //放行的路径
        String[] urls = {
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //判断是否属于要拦截的路径，不是则放行
        boolean flag = checkURL(urls, requestURI);
        if (flag) {
            filterChain.doFilter(request, response);
            return;
        }

        //判断是否登录，登录则放行
        HttpSession session = request.getSession();
        Object employee = session.getAttribute("employee");
        if (employee != null) {
            filterChain.doFilter(request, response);
            return;
        }

        Object user = session.getAttribute("user");
        if (user != null) {
            filterChain.doFilter(request, response);
            return;
        }

        //响应拦截信息给前端
        String msgJson = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(msgJson);
    }

    private boolean checkURL(String[] urls, String requestURI) {
        for (String url : urls) {
            if (antPathMatcher.match(url, requestURI)) {
                return true;
            }
        }

        return false;
    }

}
